package pay.activity;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.TextPaint;
import android.text.TextUtils;
import android.text.method.LinkMovementMethod;
import android.text.style.ClickableSpan;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alipay.sdk.app.PayTask;
import com.example.xuegengwang.xuegengwang.R;
import com.example.xuegengwang.xuegengwang.wxapi.MyWxApi;
import com.google.gson.Gson;

import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.view.annotation.ContentView;
import org.xutils.view.annotation.ViewInject;

import java.util.HashMap;
import java.util.Map;

import pay.bean.EvaluatePayBean;
import willevaluate.web.Protocol;
import common.BaseActivity;
import common.Constant;
import https.InterNetController;
import pay.bean.WxPayBean;
import utils.MyLogUtils;
import utils.ToastUtils;

/**
 * Created by Administrator on 2017/4/15.
 * 支付汇总页面
 */
@ContentView(R.layout.college_evaluate)
public class Pay extends BaseActivity implements View.OnClickListener {
    @ViewInject(R.id.college_evaluate_back)
    private ImageView college_evaluate_back;//返回
    @ViewInject(R.id.college_evaluate_cancel)
    private TextView college_evaluate_cancel;//取消
    @ViewInject(R.id.college_evaluate_price)
    private TextView college_evaluate_price;//价格
    @ViewInject(R.id.college_evaluate_weixin_layout)
    private RelativeLayout college_evaluate_weixin_layout;//微信支付
    @ViewInject(R.id.college_evaluate_zhifubao_layout)
    private RelativeLayout college_evaluate_zhifubao_layout;//支付宝支付
    //    @ViewInject(R.id.college_evaluate_jinzhao_layout)
    //    private RelativeLayout college_evaluate_jinzhao_layout;//今朝优惠券
    @ViewInject(R.id.college_evaluate_invite_code_layout)
    private RelativeLayout college_evaluate_invite_code_layout;//邀请码
    @ViewInject(R.id.college_evaluate_invite_code_edt)
    private EditText college_evaluate_invite_code_edt;//邀请码输入框
    @ViewInject(R.id.college_evaluate_weixin_check)
    private ImageView college_evaluate_weixin_check;//选择微信
    @ViewInject(R.id.college_evaluate_zhifubao_check)
    private ImageView college_evaluate_zhifubao_check;//选择支付宝
    @ViewInject(R.id.college_evaluate_protocol_layout)
    private LinearLayout college_evaluate_protocol_layout;//协议
    @ViewInject(R.id.college_evaluate_protocol_check)
    private ImageView college_evaluate_protocol_check;//同意协议
    @ViewInject(R.id.college_evaluate_protocol)
    private TextView college_evaluate_protocol;//协议的文字
    @ViewInject(R.id.college_evaluate_confirm_btn)
    private TextView college_evaluate_confirm_btn;//确认支付

    private int price;//金额，分为单位-------必填
    private String payType;//订单类型 questionwatch/questionpublic/questionprivate/evaluate/submit

    private String content;//问题内容
    private String answerer_id;//回答者id
    private String dialog_id;//查看问题用的
    private int position;//查看问题位置
    private String orderid;//微信订单id，用于查询
    private String out_trade_id;//支付宝订单id，用于查询

    private final int WEIXIN_PAY = 0;
    private final int ZHIFUBAO_PAY = 1;
    private final int QUERY_ORDER = 2;//查询订单
    private final int EVALUTEPAY = 3;//志愿评估200块
    private final int SUBMITPAY = 4;//2000/3000志愿评估
//    private boolean evalutePay;//志愿评估给钱
    private boolean expertEvaluatePay;//付费3800//5800//8800用的;

    private final int SDK_PAY_FLAG = 2;

    private int pay_way = -1;//支付方式
    private boolean agree_protocol = true;//同意协议

    private MyWeiXinPayReceiver myWeiXinPayReceiver;
    private static final String TAG = "Pay";

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case SDK_PAY_FLAG:
                    //支付宝支付完成
                    Map<String, String> result = (Map<String, String>) msg.obj;
                    String resultStatus = result.get("resultStatus");
                    if (resultStatus != null) {
                        MyLogUtils.e(TAG, resultStatus);
                        if ("9000".equals(resultStatus)) {
                            queryZhufubaoOrder();
                        }
                    }
                    break;
                case Constant.ERROR_CODE_SUCCESS://成功返回
                    switch (msg.arg1) {
                        case WEIXIN_PAY:
                            Gson gson = new Gson();
                            WxPayBean wxPayBean = gson.fromJson((String) msg.obj, WxPayBean.class);
                            if (wxPayBean != null) {
                                MyWxApi.Pay(Pay.this, wxPayBean);
                                orderid = wxPayBean.getOrderid();
                            }
                            break;
                        case ZHIFUBAO_PAY:
                            //提问查看问题用的
                            try {
                                JSONObject jsonObject = new JSONObject(String.valueOf(msg.obj));
                                out_trade_id = jsonObject.getString("out_trade_id");
                                String orderString = jsonObject.getString("orderString");
                                String replaceOrderString = orderString.replace("&amp;", "&");
                                nativeZhifubaoPay(replaceOrderString);
                            } catch (JSONException e) {
                                MyLogUtils.e(TAG, "订单异常");
                                ToastUtils.shortToast("订单异常");
                            }
                            break;
                        case QUERY_ORDER:
                            try {
                                JSONObject jsonObject = new JSONObject(String.valueOf(msg.obj));
                                String err_code = jsonObject.getString("err_code");
                                if ("0".equals(err_code)) {
                                    Intent i = new Intent();
                                    i.putExtra("position", position);//传出数组位置
                                    i.putExtra("orderid",orderid);//传出微信orderid
                                    i.putExtra("out_trade_id",out_trade_id);//传出支付宝orderid
                                    Pay.this.setResult(Constant.PAY_SUCCESS, i);
                                    Pay.this.finish();
                                } else if ("2".equals(err_code)) {
                                    //支付中
                                    queryWeixinOrder();
                                }
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                            break;
                        case EVALUTEPAY:
                            //志愿评估的
                            Gson g = new Gson();
                            if (pay_way == WEIXIN_PAY) {
                                //微信下单200
                                EvaluatePayBean evaluatePayBean = g.fromJson((String) msg.obj, EvaluatePayBean.class);
                                if (evaluatePayBean != null) {
                                    EvaluatePayBean.WxparamBean wxparam = evaluatePayBean.getWxparam();
                                    if (wxparam != null) {
                                        WxPayBean wxPayBean1 = new WxPayBean();
                                        wxPayBean1.setAppId(wxparam.getAppid());
                                        wxPayBean1.setNonceStr(wxparam.getNoncestr());
                                        wxPayBean1.setOrderid(wxparam.getOrderid());
                                        wxPayBean1.setPartnerid(wxparam.getPartnerid());
                                        wxPayBean1.setPrepayid(wxparam.getPrepayid());
                                        wxPayBean1.setSign(wxparam.getSign());
                                        wxPayBean1.setTimeStamp(String.valueOf(wxparam.getTimestamp()));
                                        MyWxApi.Pay(Pay.this, wxPayBean1);
                                        orderid = wxPayBean1.getOrderid();
                                    }
                                }
                            } else {
                                //支付宝下单200
                                EvaluatePayBean evaluatePayBean = g.fromJson((String) msg.obj, EvaluatePayBean.class);
                                if (evaluatePayBean != null) {
                                    String aliparam = evaluatePayBean.getAliparam();
                                    out_trade_id = evaluatePayBean.getOut_trade_id();
                                    String aliparam1 = aliparam.replace("&amp;", "&");
                                    nativeZhifubaoPay(aliparam1);
                                }
                            }
                            break;
                        case SUBMITPAY:
                            //2000/3000志愿评估
                            Gson g1 = new Gson();
                            switch (pay_way){
                                case WEIXIN_PAY:
                                    //微信下单200
                                    EvaluatePayBean evaluatePayBean = g1.fromJson((String) msg.obj, EvaluatePayBean.class);
                                    if (evaluatePayBean != null) {
                                        EvaluatePayBean.WxparamBean wxparam = evaluatePayBean.getWxparam();
                                        if (wxparam != null) {
                                            WxPayBean wxPayBean1 = new WxPayBean();
                                            wxPayBean1.setAppId(wxparam.getAppid());
                                            wxPayBean1.setNonceStr(wxparam.getNoncestr());
                                            wxPayBean1.setOrderid(wxparam.getOrderid());
                                            wxPayBean1.setPartnerid(wxparam.getPartnerid());
                                            wxPayBean1.setPrepayid(wxparam.getPrepayid());
                                            wxPayBean1.setSign(wxparam.getSign());
                                            wxPayBean1.setTimeStamp(String.valueOf(wxparam.getTimestamp()));
                                            MyWxApi.Pay(Pay.this, wxPayBean1);
                                            orderid = wxPayBean1.getOrderid();
                                            MyLogUtils.e(TAG,"weixinpay+"+orderid);
                                        }
                                    }
                                    break;
                                case ZHIFUBAO_PAY:
                                    //支付宝下单200
                                    try {
                                        JSONObject jsonObject = new JSONObject(String.valueOf(msg.obj));
                                        String aliparam = jsonObject.getString("aliparam");
                                        out_trade_id = jsonObject.getString("orderid");
                                        String aliparam1 = aliparam.replace("&amp;", "&");
                                        nativeZhifubaoPay(aliparam1);
                                    } catch (JSONException e) {
                                        e.printStackTrace();
                                    }
                                    break;
                                default:
                                    break;
                            }
                            break;
                        default:
                            break;
                    }
                    break;
                default:
                    break;
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        payType = getIntent().getStringExtra("payType");
        price = getIntent().getIntExtra("price", 0);
        content = getIntent().getStringExtra("content");
        answerer_id = getIntent().getStringExtra("answerer_id");
        dialog_id = getIntent().getStringExtra("dialog_id");
        position = getIntent().getIntExtra("position", 0);
        //付费200的时候用的
//        evalutePay = getIntent().getBooleanExtra("evalutePay", false);
        //付费3800/5800//8800用的;
        expertEvaluatePay = getIntent().getBooleanExtra("expertEvaluatePay", false);

        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(Constant.WEIXIN_ACITION_HASPAY);
        myWeiXinPayReceiver = new MyWeiXinPayReceiver();
        registerReceiver(myWeiXinPayReceiver, intentFilter);
        initView();
    }

    private void initView() {
        college_evaluate_back.setOnClickListener(this);
        college_evaluate_cancel.setOnClickListener(this);
        college_evaluate_weixin_layout.setOnClickListener(this);
        college_evaluate_zhifubao_layout.setOnClickListener(this);
//        college_evaluate_jinzhao_layout.setOnClickListener(this);
        college_evaluate_confirm_btn.setText("确认支付¥" + (price / 100.00));
        college_evaluate_confirm_btn.setOnClickListener(this);
        college_evaluate_protocol_check.setOnClickListener(this);
        college_evaluate_protocol_layout.setOnClickListener(this);
        college_evaluate_price.setText("¥ " + (price / 100.00));

        //当选择2500/5000志愿评估时
        if (expertEvaluatePay) {
            college_evaluate_invite_code_layout.setVisibility(View.VISIBLE);
        } else {
            college_evaluate_invite_code_layout.setVisibility(View.GONE);
        }

        SpannableString content = new SpannableString("我已阅读并同意《今朝服务协议》");
        ClickableSpan myClickableSpan1 = new ClickableSpan() {
            @Override
            public void updateDrawState(TextPaint ds) {
                int color = Pay.this.getResources().getColor(R.color.common_color);
                ds.setColor(color);
                ds.setUnderlineText(false); //去掉下划线
            }

            @Override
            public void onClick(View widget) {
                Intent i = new Intent(Pay.this, Protocol.class);
                startActivity(i);
            }
        };
        content.setSpan(myClickableSpan1, 7, content.length(), Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
        college_evaluate_protocol.setText(content);
        college_evaluate_protocol.setMovementMethod(LinkMovementMethod.getInstance());
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.college_evaluate_back:
            case R.id.college_evaluate_cancel:
                Pay.this.finish();
                break;
            case R.id.college_evaluate_weixin_layout:
                //微信支付
                pay_way = WEIXIN_PAY;
                college_evaluate_weixin_check.setImageResource(R.mipmap.college_evaluate_checked_ima);
                college_evaluate_zhifubao_check.setImageResource(R.mipmap.college_evaluate_check_ima);
                break;
            case R.id.college_evaluate_zhifubao_layout:
                //支付宝支付
                pay_way = ZHIFUBAO_PAY;
                college_evaluate_zhifubao_check.setImageResource(R.mipmap.college_evaluate_checked_ima);
                college_evaluate_weixin_check.setImageResource(R.mipmap.college_evaluate_check_ima);
                break;
//            case R.id.college_evaluate_jinzhao_layout:
//                intent.setClass(Pay.this, Coupon1.class);
//                startActivity(intent);
//                break;
            case R.id.college_evaluate_confirm_btn:
                //确认支付
                if (agree_protocol) {
//                    if (evalutePay) {
//                        evalutePay();
//                    }
                    if (expertEvaluatePay) {
                        submitPay();
                    } else {
                        switch (pay_way) {
                            case WEIXIN_PAY:
                                WXPay();
                                break;
                            case ZHIFUBAO_PAY:
                                // 必须异步调用
                                zhifubaoPay();
                                break;
                            default:
                                ToastUtils.shortToast("请选择支付方式");
                                break;
                        }
                    }
                } else {
                    ToastUtils.shortToast("请选择同意《今朝服务协议》");
                }
                break;
            case R.id.college_evaluate_protocol_layout:
            case R.id.college_evaluate_protocol_check:
                if (!agree_protocol) {
                    //同意协议
                    college_evaluate_protocol_check.setImageResource(R.mipmap.college_evaluate_checked_ima);
                    agree_protocol = true;
                } else {
                    college_evaluate_protocol_check.setImageResource(R.mipmap.college_evaluate_check_ima);
                    agree_protocol = false;
                }
                break;
            default:
                break;
        }
    }

    //本地调起支付宝支付
    private void nativeZhifubaoPay(final String orderInfo) {
        Runnable payRunnable = new Runnable() {
            @Override
            public void run() {
                PayTask alipay = new PayTask(Pay.this);
                Map<String, String> result = alipay.payV2(orderInfo, false);
                Message msg = new Message();
                msg.what = SDK_PAY_FLAG;
                msg.obj = result;
                handler.sendMessage(msg);
            }
        };
        Thread payThread = new Thread(payRunnable);
        payThread.start();
    }

    private void WXPay() {
        HashMap<String, String> hashMap = new HashMap<>();
        hashMap.put("body", "今朝升学--付费提问");
        hashMap.put("total_fee", String.valueOf(price));
        hashMap.put("trade_type", "APP");
        if (dialog_id != null && !TextUtils.isEmpty(dialog_id)) {
            hashMap.put("dialog_id", dialog_id);
            new InterNetController(Pay.this, Constant.WATCHANSWER, handler, hashMap, pay_way);
        } else {
            if (content != null && !TextUtils.isEmpty(content)) {
                hashMap.put("content", content);
            }
            if (answerer_id != null && !TextUtils.isEmpty(answerer_id)) {
                hashMap.put("answerer_id", answerer_id);
            }
            new InterNetController(Pay.this, Constant.COMMITWXORDER, handler, hashMap, pay_way);
        }
    }

    //支付宝付费
    private void zhifubaoPay() {
        HashMap<String, String> hashMap = new HashMap<>();
        hashMap.put("body", "今朝升学--付费提问");
        hashMap.put("total_amount", String.valueOf(price));
        if (dialog_id != null && !TextUtils.isEmpty(dialog_id)) {
            hashMap.put("subject", "查看问题");
            hashMap.put("dialog_id", dialog_id);
            new InterNetController(Pay.this, Constant.WATCHALIANSWER, handler, hashMap, pay_way);
        } else {
            //提问用的
            if (price == Constant.QUESTIONPRIVATE_PRICE) {
                hashMap.put("subject", "私密提问");
            } else if (price == Constant.QUESTIONPUBLIC_PRICE) {
                hashMap.put("subject", "公开提问");
            }
            if (content != null) {
                hashMap.put("content", content);
            }
            if (answerer_id != null) {
                hashMap.put("answerer_id", answerer_id);
            }
            new InterNetController(Pay.this, Constant.COMMITALIORDER, handler, hashMap, pay_way);
        }
    }

    //微信查看订单
    private void queryWeixinOrder() {
        MyLogUtils.e(TAG,"queryWeixinOrder+"+orderid);
        HashMap<String, String> hashMap = new HashMap<>();
        hashMap.put("orderid", orderid);
        hashMap.put("type", payType);
        new InterNetController(this, Constant.QUERYORDER, handler, hashMap, QUERY_ORDER, false);
    }

    //支付宝订单查询
    private void queryZhufubaoOrder() {
        HashMap<String, String> hashMap = new HashMap<>();
        hashMap.put("out_trade_id", out_trade_id);
        hashMap.put("type", payType);
        new InterNetController(this, Constant.ALISUCCESS, handler, hashMap, QUERY_ORDER, false);
    }

    //微信支付情况回调
    public class MyWeiXinPayReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent != null) {
                int code = intent.getIntExtra("code", -2);
                if (code == 0) {
                    //显示支付成功的页面和需要的操作
                    queryWeixinOrder();
                }
                if (code == -1) {
                    //错误
                    ToastUtils.shortToast("支付错误");
                }
                if (code == -2) {
                    //用户取消
                    ToastUtils.shortToast("取消支付");
                }
            }
        }
    }

    //200志愿评估付费
//    private void evalutePay() {
//        HashMap<String, String> hashMap = new HashMap<>();
//        hashMap.put("body", "志愿评估");
//        hashMap.put("subject", "今朝升学");
//        hashMap.put("price", String.valueOf(Constant.EVALUTE_PRICE));
//        String type1;
//        switch (pay_way) {
//            case WEIXIN_PAY:
//                type1 = "wx";
//                break;
//            case ZHIFUBAO_PAY:
//                type1 = "ali";
//                break;
//            default:
//                ToastUtils.shortToast("请选择支付方式");
//                return;
//        }
//        hashMap.put("type", type1);
//        new InterNetController(this, Constant.EVALUTEPAY, handler, hashMap, EVALUTEPAY);
//    }

    //3800/5800//8800付费评估
    private void submitPay() {
        String inviteCode = college_evaluate_invite_code_edt.getText().toString().trim();

        HashMap<String, String> hashMap = new HashMap<>();
        hashMap.put("body", "志愿填报");
        hashMap.put("subject", "今朝升学");
        if (!TextUtils.isEmpty(inviteCode)) {
            //有邀请码
            int price = (int) (this.price * Constant.DISCOUNT);
            hashMap.put("price", String.valueOf(price));
            hashMap.put("invite_code", inviteCode);
        } else {
            //无邀请码
            hashMap.put("price", String.valueOf(price));
        }
        switch (pay_way) {
            case WEIXIN_PAY:
                hashMap.put("type", "wx");
                break;
            case ZHIFUBAO_PAY:
                hashMap.put("type", "ali");
                break;
            default:
                ToastUtils.shortToast("请选择支付方式");
                return;
        }
        new InterNetController(this, Constant.SUBMITPAY, handler, hashMap, SUBMITPAY);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (myWeiXinPayReceiver != null) {
            unregisterReceiver(myWeiXinPayReceiver);
        }
    }
}
